package com.bmp.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

import com.bmp.dao.BugDao;
import com.bmp.model.Bug;
import com.bmp.model.vo.BugVoProModUser;
import com.bmp.util.HibernateUtil;
@Component("bugDao")
public class BugDaoImpl implements BugDao {
	private HibernateTemplate hibernateTemplate;

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	@Resource
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}
	public void deleteBugById(int id) {
		Bug b = this.getBugById(id);
		this.hibernateTemplate.delete(b);
	}

	public Bug getBugById(int id) {
		return (Bug)this.hibernateTemplate.get(Bug.class, id);
	}

	public void insertBug(Bug b) {
		this.hibernateTemplate.save(b);
	}

	public void updateBug(Bug b) {
		this.hibernateTemplate.update(b);
	}
	//获取每页显示的bug信息
	@SuppressWarnings("unchecked")
	public List<BugVoProModUser> getBug(int page, int rows) {
		List<BugVoProModUser> list = null;
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.getCurrentSession();
		session.beginTransaction();
		String sql = "select new com.bmp.model.vo.BugVoProModUser(b.id,b.title,b.severity,b.priority,b.status,b.des,u.name,b.find_date,u1.name,p.p_name,m.m_name,b.fix_date,b.check_date) from Bug b,Project p,Module m,User u,User u1 where b.finder_id = u.id and b.appoint_id = u1.id and b.pro_id = p.id and b.mode_id = m.id";
		list = session.createQuery(sql).setFirstResult((page-1)*rows).setMaxResults(rows).list();
		session.getTransaction().commit();
		return list;
	}
	//获取总记录数
	public int getTotalPages() {
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.getCurrentSession();
		session.beginTransaction();
		String sql = "select count(*) from Bug b";
		long count = (Long)session.createQuery(sql).uniqueResult();
		session.getTransaction().commit();
		return (int)count;
	}

	public List<Bug> getBugByUserId(int userId) {
		List<Bug> bugs = hibernateTemplate.find("from Bug b where b.finder_id = '"+userId+"'");
		return bugs;
	}

	public List<Bug> getBugByProjectId(int projectId) {
		List<Bug> bugs = hibernateTemplate.find("from Bug b where b.pro_id = '"+projectId+"'");
		return bugs;
	}

	public List<Bug> getBugByModuleId(int moduleId) {
		List<Bug> bugs = hibernateTemplate.find("from Bug b where b.mode_id = '"+moduleId+"'");
		return bugs;
	}

	public List<Bug> getBugByAppointId(int apointId) {
		List<Bug> bugs = hibernateTemplate.find("from Bug b where b.appoint_id = '"+apointId+"'");
		return bugs;
	}

}
